import {LockOutlined, UserOutlined} from '@ant-design/icons';
import {LoginForm, ProFormText} from '@ant-design/pro-components';
import {FormattedMessage, Helmet, SelectLang, useIntl} from '@umijs/max';
import {Alert, App, Tabs} from 'antd';
import {createStyles} from 'antd-style';
import React, {useState} from 'react';
import {Footer} from '@/components';
import {PLANET_LINK, SYSTEM_LOGO} from '@/constants';
import {register} from '@/services/ant-design-pro/api';
import Settings from '../../../../config/defaultSettings';
import {Link} from "@@/exports";

const useStyles = createStyles(({token}) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
    // 注册页面返回登录页面链接的样式
    // 页面的右下角
    linkToLogin: {
      position: 'absolute', // 或者使用 'fixed'
      bottom: '16px',
      right: '16px',
    },
  };
});

const Lang = () => {
  const {styles} = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang/>}
    </div>
  );
};

const Register: React.FC = () => {
  const [type, setType] = useState<string>('account');
  const {styles} = useStyles();
  const {message} = App.useApp();
  const intl = useIntl();

  // 表单提交
  const handleSubmit = async (values: API.RegisterParams) => {
    const {checkPassword, userPassword} = values;
    // 校验
    if (userPassword !== checkPassword) {
      message.error('密码和确认密码不一致！');
      return;
    }

    try {
      // 注册
      // const res = await register({ ...values, type });
      const id = await register({...values, type});

      // if (res.code === 0 && res.data > 0) {
      if (id) {

        const defaultLoginSuccessMessage = '注册成功！';
        message.success(defaultLoginSuccessMessage);

        // 延迟跳转，让用户看到提示
        setTimeout(() => {
          const urlParams = new URL(window.location.href).searchParams;
          window.location.href = urlParams.get('redirect') || '/';
        }, 1500); // 1.5秒后跳转
        return;
      }
      // else {
      //   // 根据后端返回的描述进行弹窗提醒抛出异常，给下面的异常捕获提供信息
      //   throw new Error(res.description)
      // }
      // console.log(res);
    } catch (error: any) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '注册失败，请重试！',
      });
      console.log(error);
      // 根据上面的异常抛出的信息进行弹窗提醒
      // message.error(error.message ?? defaultLoginFailureMessage);
      message.error(defaultLoginFailureMessage);

    }
  };

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '注册页',
          })}
          {Settings.title && ` - ${Settings.title}`}
        </title>
      </Helmet>
      <Lang/>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          // 这里翻找到源码之后在这里仿照进行添加
          submitter={{
            searchConfig: {
              submitText: '注册',
            },
          }}
          logo={<img alt="logo" src={SYSTEM_LOGO}/>}
          title="编程导航知识星球"
          subTitle={
            <a href={PLANET_LINK} target="_blank" rel="noreferrer">
              最好的编程学习圈子
            </a>
          }
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.RegisterParams);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码注册',
              },
            ]}
          />

          {type === 'account' && (
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined/>,
                }}
                placeholder={'账号: admin or user'}
                rules={[
                  {
                    required: true,
                    message: '账号是必填项!',
                  },
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined/>,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                  {
                    min: 8,
                    type: 'string',
                    message: '密码长度不能小于8位',
                  },
                ]}
              />
              <ProFormText.Password
                name="checkPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined/>,
                }}
                placeholder={'请再次输入密码'}
                rules={[
                  {
                    required: true,
                    message: '确认密码是必填项!',
                  },
                  {
                    min: 8,
                    type: 'string',
                    message: '密码长度不能小于8位',
                  },
                ]}
              />
              <ProFormText
                name="planetCode"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined/>,
                }}
                placeholder={'请输入星球编号'}
                rules={[
                  {
                    required: true,
                    message: '星球编号必填项!',
                  },
                ]}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          ></div>

        </LoginForm>
      </div>
      {/*返回到登录页面*/}
      <Link to="/user/login" className={styles.linkToLogin}>返回登录页面</Link>
      <Footer/>

    </div>
  );
};

export default Register;
